using System;
using System.Reflection;
using System.Text;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;
using InfoJetSoft.Service.ManagedCode;

namespace InfoJetSoft.Service.Worker
{
	/// <summary>
	/// Summary description for ManagedCodeOnSubmitRequestWorker.
	/// </summary>
	class ManagedCodeOnSaveFormWorker
	{
		
		public static void OnSaveForm(Form form)
		{
			if( form.Manifest.ManagedAssembly == null || form.Manifest.ManagedAssembly.ModelType == null )
			{
				return;
			}

			if( !FormSession.hasCacheXml( form ) )
			{
				return;
			}

			ManagedCodeUtil.createModel( form );
			object model = form.ManagedCodeModel;

			MethodInfo onSaveForm = ManagedCodeUtil.findMethod( model, "InfoJetService_OnSaveForm" );
			if( onSaveForm == null )
			{
				return;
			}

			//CID 0474 //2009.12.23 //Begin
			form.Logger.LogUpdate(null);
			//CID 0474 //2009.12.23 //End

			XDocument xdoc = new XDocument( form );
			Application app = new Application( form );
			DocReturnEvent docReturnEvent = new DocReturnEvent( xdoc );

			try
			{

				MethodInfo startup = ManagedCodeUtil.findMethod( model, "_Startup" );
				startup.Invoke( model, new object[]{ app, xdoc } );

				object result = onSaveForm.Invoke( model, new object[]{ docReturnEvent } );
			
				MethodInfo shutdown = ManagedCodeUtil.findMethod( model, "_Shutdown" );
				shutdown.Invoke( model, new object[]{} );

				XmlDocument reloadDoc = (XmlDocument)result;
				DOMUtil.removeJetId( reloadDoc );
				
				form.WholeXmlDoc = reloadDoc;
			}
			catch( Exception e )
			{
                FormUtil.addInnerExceptionMassage(form, onSaveForm.Name, e);
			}
		}

	}
}
